package com.binbinyl.model.remote

import com.binbinyl.helper.Util
import com.binbinyl.helper.network.RequestHandler
import com.binbinyl.model.remote.exception.ApiException
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response

/**
 * request 拦截器，行为实现类
 */
open class DefaultRequestHandler : RequestHandler {

    override fun beforeRequest(request: Request, chain: Interceptor.Chain): Request {
        return request
    }

    override fun afterRequest(response: Response, chain: Interceptor.Chain): Response {
        var e: ApiException? = null
        if (401 == response.code()) {
            throw ApiException("登录已过期,请重新登录!")
        } else if (403 == response.code()) {
            e = ApiException("禁止访问!")
        } else if (404 == response.code()) {
            e = ApiException("链接错误")
        } else if (503 == response.code()) {
            e = ApiException("服务器升级中!")
        } else if (response.code() > 300) {
            val message = response.body()!!.string()
            e = if (Util.checkNull(message)) {
                ApiException("服务器内部错误!")
            } else {
                ApiException(message)
            }
        }
        if (!Util.checkNull(e)) {
            throw e!!
        }
        return response
    }
}